package ZS1;

import java.util.Stack;

/**
 * 最小栈
 * 请设计一个栈，除了常规栈支持的pop与push函数以外，还支持min函数，
 * 该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。
 */
public class MinStackTest {
    public static void main(String[] args) {
        MinStack minStack = new MinStack();
        minStack.push(4);
        minStack.push(5);
        minStack.push(2);
        minStack.push(1);
        minStack.push(-1);
        minStack.push(9);
        minStack.show();
        System.out.println(minStack.getMin());
    }
}

// 利用双栈来实现最小栈
class MinStack{

    Stack<Integer> valStack = new Stack<>(); // 存放真实值的栈
    Stack<Integer> minStack = new Stack<>(); // 存放最小值的栈

    /** initialize your data structure here. */
    public MinStack() {

    }

    public void push(int x) {
        if(valStack.isEmpty()){
            valStack.push(x);
            minStack.push(x);
        }else{
            valStack.push(x);
            minStack.push(Math.min(x, minStack.peek()));
        }
    }

    public void pop() {
        valStack.pop();
        minStack.pop();
    }

    public int top() {
        return valStack.peek();
    }

    public int getMin() {
        if(minStack.isEmpty()){
            return Integer.MIN_VALUE;
        }
        return minStack.peek();
    }

    public void show(){
        System.out.println(valStack);
        System.out.println(minStack);

    }

}